import Vue from 'vue'
import Vuex from 'vuex'
import router, {resetRouter} from "@/router";
import request from '../utils/request'
import SockJs from 'sockjs-client'
import Stomp from 'stompjs'

Vue.use(Vuex)
const now = new Date();
const store = new Vuex.Store({
    state: {
        sessions: [],
        admins: [],
        currentSessionId: -1,
        filterKey: '',
        currentPathName: '',
        stomp: null
    },
    actions: {
        connect(context) {
            context.state.stomp = Stomp.over(new SockJs('/ws/ep'))
            let user = localStorage.getItem("user")
            let token = user.token
            context.state.stomp.connect({'Auth-Token': token}, success => {
                context.state.stomp.subscribe('/queue/chat', message => {
                    console.log(message.body);
                })
            }, error => {

            })
        },
        initData(context) {
            request.get("/user").then(resp => {
                if (resp) {
                    context.commit('INIT_ADMINS', resp.data)
                }
            })

        }
    },

    mutations: {
        changeCurrentSessionId(state, id) {
            state.currentSessionId = id;
        },
        addMessage(state, msg) {
            state.sessions[state.currentSessionId - 1].messages.push({
                content: msg,
                date: new Date(),
                self: true
            })
        },
        INIT_DATA(state) {
            // 浏览器历史聊天记录
            /* let data = localStorage.getItem('vue-chat-session');
             //console.log(data)
             if (data) {
                 state.sessions = JSON.parse(data);
             }*/
        },
        INIT_ADMINS(state, data) {
            state.admins = data;
        },
        setPath(state) {
            state.currentPathName = localStorage.getItem("currentPathName")
        },
        logout() {
            // 清空缓存
            localStorage.removeItem("user")
            localStorage.removeItem("menus")
            router.push("/login")

            // 重置路由
            resetRouter()
        }
    }
})
store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

export default store
